<?php
namespace frontend\controllers;

use Yii;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

use yii\rbac\DbManager;
/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
		// if(\Yii::$app->user){
			// echo '<pre>';
			// var_dump(\Yii::$app->user->isGuest);
			// die("111");
		// }
        return [
            'access' => [
                'class' => AccessControl::className(),
                // 'only' => ['*'],
                'rules' => [
                  [
							'actions' => ['login', 'logout','signup','request-password-reset'],
							'allow' => true,
							'roles' => ['?'],
						],
						[
							// 'actions' => ['login', 'logout'],
							'allow' => true,
							'roles' => ['@'],
						],
						[
							// 'actions' => ['logout'],
							'allow' => false,
							'roles' => ['?'],
						],
               ],
					'denyCallback' => function ($rule, $action) {
						$this->redirect('/site/login');
					},
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public function actionIndex()
    {
		return $this->render('index');
    }

    public function actionLogin()
    {
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                Yii::$app->session->setFlash('error', 'There was an error sending email.');
            }

            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }

    public function actionAbout()
    {
        return $this->render('about');
    }

    public function actionSignup()
    {
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->goHome();
                }
            }
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }

    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->getSession()->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->getSession()->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->getSession()->setFlash('success', 'New password was saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }
	 
	public function actionRoleRule(){
		$auth = Yii::$app->authManager;
		// $auth->removeAll(); exit;
		// add the rule
		/*/ $rule = new \common\rbac\AuthorRule;
		// $auth->add($rule);
		// add the "updateOwnPost" permission and associate the rule with it.
		// $updateOwnPost = $auth->createPermission('updateOwnPost');
		// $updateOwnPost->description = 'Update own post';
		// $updateOwnPost->ruleName = $rule->name;
		// $auth->add($updateOwnPost);
		// "updateOwnPost" will be used from "updatePost"
		$auth->addChild($updateOwnPost, $updatePost);
		// allow "author" to update their own posts
		$auth->addChild($author, $updateOwnPost);
		*/
		//view chung tu
		$viewChungTu = $auth->createPermission('viewChungTu');
		$viewChungTu->description = 'Read/view chung tu';
		$auth->add($viewChungTu);
		//edit chung tu
		$editChungTu = $auth->createPermission('editChungTu');
		$editChungTu->description = 'Edit/Create chung tu';
		$auth->add($editChungTu);	
		//edit chung tu
		$deleteChungTu = $auth->createPermission('deleteChungTu');
		$deleteChungTu->description = 'Delete chung tu';
		$auth->add($deleteChungTu);
		//edit user
		$editUser = $auth->createPermission('editUser');
		$editUser->description = 'Edit/Create user';
		$auth->add($editUser);
		//delete user
		$deleteUser = $auth->createPermission('deleteUser');
		$deleteUser->description = 'Delete user';
		$auth->add($deleteUser);
		//view Report
		$viewReport = $auth->createPermission('viewReport');
		$viewReport->description = 'Read/view report';
		$auth->add($viewReport);
		//Manage Options
		$manageOption = $auth->createPermission('manageOption');
		$manageOption->description = 'Manage Options';
		$auth->add($manageOption);
		// add "viewer" role
		$viewer = $auth->createRole('viewer');
		$auth->add($viewer);
		$auth->addChild($viewer, $viewChungTu);
		// add "reporter" role
		$reporter = $auth->createRole('reporter');
		$auth->add($reporter);
		$auth->addChild($reporter, $viewReport);
		// add "typer" role
		$typer = $auth->createRole('typer');
		$auth->add($typer);
		$auth->addChild($typer, $editChungTu);
		$auth->addChild($typer, $deleteChungTu);
		$auth->addChild($typer, $viewer);
		// add "accountant" role
		$accountant = $auth->createRole('accountant');
		$auth->add($accountant);
		$auth->addChild($accountant, $editUser);
		$auth->addChild($accountant, $deleteUser);
		$auth->addChild($accountant, $manageOption);		
		$auth->addChild($accountant, $typer);
		$auth->addChild($accountant, $reporter);
		//
		// add "admin" role 
		$admin = $auth->createRole('admin');
		$auth->add($admin);
		// $auth->addChild($admin, $updatePost);
		$auth->addChild($admin, $accountant);

		// Assign roles to users. 1 and 2 are IDs returned by IdentityInterface::getId()
		// usually implemented in your User model.
		$auth->assign($accountant, 2);
		$auth->assign($admin, 1);
		// $user = $auth->createRole('user');		
		// $auth->add($user);
		// $createPost = $auth->getPermission('createPost');
		// $auth->addChild($user, $createPost);
	}
	
	public function actionAccess(){
		if (\Yii::$app->user->can('viewChungTu',['post'=>'123'])) {
			echo 'U Post';
		}else
			echo 'Can not';
	}
	// $session = Yii::$app->getSession();
	// $session->remove($this->idParam);
	// $session->set($this->idParam, $identity->getId());
}
